// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#pragma once

namespace coin2::exchange::maicoin::order_v2 {

inline std::optional<int64_t> GetErrorCode(const rapidjson::GenericValue<rapidjson::UTF8<>>& json) {
  if (!json.IsObject() || !json.HasMember("error")) {
    return std::nullopt;
  }

  const auto& error = json["error"];
  if (!error.HasMember("code")) {
    return std::nullopt;
  }

  return stoll(error["code"].GetString());
}

inline std::optional<std::string> GetErrorMsg(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json) {
  if (!json.IsObject() || !json.HasMember("error")) {
    return std::nullopt;
  }

  const auto& error = json["error"];
  if (!error.HasMember("message")) {
    return std::nullopt;
  }

  return error["message"].GetString();
}

inline coin::proto::OrderErrorCode GetOrderErrorCode(int64_t exchange_error_code) {
  using coin::proto::OrderErrorCode;
  auto result = OrderErrorCode::ORDER_UNKNOWN_ERROR;

  if (exchange_error_code == 0) {
    result = OrderErrorCode::ORDER_NO_ERROR;
  } else if (exchange_error_code == 2018) {
    result = OrderErrorCode::SUBMIT_ORDER_INSUFFICIENT_FUND;
  } else if (exchange_error_code == 2004) {
    result = OrderErrorCode::ORDER_NOT_FOUND;
  } else {
    LOG(ERROR) << "[GetOrderErrorCode] " << exchange_error_code;
  }

  return result;
}

}  // namespace coin2::exchange::maicoin::order_v2
